import sys
sys.path.append('..')
from model.CVE import CVE
import service.CommitService as CommitService
import dao.CVEDao as CVEDao
import threading
import time

def _get_cve(cve_id):
    # 如果数据库没有获取到，则从社区网站获取CVE信息，最后保存到数据库中
    # return {'mainline': mainline_commitId, 'stable/5.10': stable_commitId, 'url': url, 'title': title, 'fixes': fixes_commitId, 'all_match_text': all_match_text}
    # requests.exceptions.ConnectionError,b捕获异常，重试机制
    max_retry = 3
    try:
        cve_info = CommitService.getCommitIdFromCVE(cve_id)
    except Exception as e:
        print(f'Error: {e}')
        for i in range(max_retry):
            print(f'Retry {i+1} times')
            try:
                time.sleep(0.5)
                cve_info = CommitService.getCommitIdFromCVE(cve_id)
                break
            except Exception as e:
                print(f'Error: {e}')

    if cve_info is None:
        # 保存到数据库中
        CVEDao.save_cve(CVE(cve_id, None, None, None, None, None, None))
        return CVE(cve_id, None, None, None, None, None, None)
    mainline_commitId = cve_info['mainline']
    stable_commitId = cve_info['stable/5.10']
    title = cve_info['title']
    fixes_commitId = cve_info['fixes']
    cve_url = cve_info['url']
    all_match_text = cve_info['all_match_text']
    # 保存到数据库中
    CVEDao.save_cve(CVE(cve_id, mainline_commitId, stable_commitId, title, fixes_commitId, cve_url, all_match_text))
    return CVE(cve_id, mainline_commitId, stable_commitId, title, fixes_commitId, cve_url,all_match_text)

# 会从社区获取到其它信息，如commitId等
# cve会乱序，因为多线程，需要注意
# def get_cve_list(cve_id_list):
#     cve_list = []
#     # 多线程获取CVE信息
#     threads = []
#     for cve_id in cve_id_list:
#         # 从数据库中获取CVE信息
#         cve_info = CVEDao.get_cve_from_db(cve_id)
#         if cve_info is not None:
#             cve_list.append(cve_info)
#             continue
#         t = threading.Thread(target=lambda temp_cve_id=cve_id: cve_list.append(_get_cve(temp_cve_id)))
#         threads.append(t)
#         t.start()
#         time.sleep(0.8)
#     for t in threads:
#         t.join()
#     return cve_list